﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.iss.inventory.BusinessLogic;
using com.iss.inventory.CustomModels;
using com.iss.inventory.Entity;

namespace Staionery_Inventory.Presentation.Search
{
    public partial class SearchItemsPage : System.Web.UI.Page
    {
        SearchController searchControl = new SearchController();
        SearchItemsModel model = new SearchItemsModel();
        SearchItemsModel resultModel;
        InvManagementEntities em = new InvManagementEntities();
     
        List<StationeryItem> itemList;

        protected void Page_Load(object sender, EventArgs e)
        {
            // if employee not logged in, reirect to login page
            if (Session["empID"] == null)
            {
                ViewState["PreviousPage"] = null;
                Response.Redirect("~/Presentation/login.aspx");

            }

            //Adding new page unload event handler
            this.Page.Unload += new EventHandler(Page_Unload);
            //Assign Login User Name
            Label lbl = this.Master.FindControl("lblLogInName") as Label;
            
            if (lbl != null)
            {
                lbl.Text = Session["UserName"].ToString();
            }
            //adding search model criteria 
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                model.getCriteriaList().Add("");
                
                //if there is search criteria in previous call, get it into model
                if (Session["searchitemsmodel"] != null)
                {
                    SearchItemsModel prevPageModel = Session["searchitemsmodel"] as SearchItemsModel;
                    model = prevPageModel;
                }
                //when page is loaded first time
                if (!IsPostBack)
                {
                    //check validation for filter
                    divtxtFilter.Attributes.Add("onkeypress", null);
           

                    btnFilter.Enabled = false;
                    rbtItemCategory.Checked = true;
                    ViewState["PreviousPage"] = Request.UrlReferrer;
                    //if search page is not from these below pages, items cannot be selected
                    if(ViewState["PreviousPage"]!=null)
                        if ((!ViewState["PreviousPage"].ToString().Contains("StockCard.aspx")) && (!ViewState["PreviousPage"].ToString().Contains("AddItemToVoucherUI.aspx")) && (!ViewState["PreviousPage"].ToString().Contains("PurchaseOrders.aspx")) && (!ViewState["PreviousPage"].ToString().Contains("StationeryRequisitionForm.aspx")))
                        btnSelectItems.Enabled = false;
                    else btnSelectItems.Enabled = true;

                    // add initializer values here
                    string checkPrevURL = Request.UrlReferrer.ToString();
                    if(checkPrevURL.Contains("PurchaseOrders.aspx"))
                    if ((model.CriteriaList[0].Length > 0 )) //if it is having supplier condition and coming from Purchasse Orders Page
                    {
                        btnFilter.Enabled = false;
                        txtFilter.Enabled = false;
                        txtFilter.Text = model.CriteriaList[0];
                        txtSearchItemName.Text = "";
                        rbtItemCategory.Checked = false;
                        rbtSupplierID.Enabled = false;
                        rbtItemCategory.Enabled = false;
                        rbtSupplierID.Checked = true;
                        btnFilter_Click(btnFilter, null);
                    }

                }
        }


        protected void Page_Unload(object sender, EventArgs e)
        {
        }

        protected void refreshCheckBoxSingleSelect(object sender, EventArgs e)
        {
            int rowIndex;
            if (model.SingleSelectMode)
            {
                CheckBox temp_cb = sender as CheckBox;
                GridViewRow gvr_selected = temp_cb.NamingContainer as GridViewRow;
                rowIndex = gvr_selected.RowIndex;
                foreach (GridViewRow gvr in gvSearchItems.Rows)
                {
                    CheckBox cb = gvr.FindControl("cbSelectItem") as CheckBox;
                    cb.Checked = false;
                }
                CheckBox cb_selected = gvSearchItems.Rows[rowIndex].FindControl("cbSelectItem") as CheckBox;
                cb_selected.Checked = true;
            }
        }

        protected void btnSearchItemName_Click(object sender, EventArgs e)
        {
            if (txtFilter.Enabled == false && rbtSupplierID.Checked == true) //when coming from purchase order page only execute below
            {
                this.btnFilter_Click(btnFilter, null);
            }
            else
            {
                // when there is search value entered in itemname text box
                if (txtSearchItemName.Text.Trim().Length != 0)
                {
                    model.getCriteriaList()[2] = txtSearchItemName.Text.Trim();
                    resultModel = searchControl.getSearchByItemName(model);
                }
                else // when no value is entered in itemname text box, get all items
                    resultModel = searchControl.getAllItemDetails(model);

                gvSearchItems.DataSource = resultModel.StationeryItemsList;
                gvSearchItems.DataBind();
                //enables filter button when there is any search results
                if (resultModel.StationeryItemsList.Count > 0) btnFilter.Enabled = true;
            }
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            //On button click, checks for filter value in filter textbox
            if(txtFilter.Text.Trim().Length!=0) {
                //if the existing search result has to be filtered by category 
                if (rbtItemCategory.Checked == true)
                {
                    model.CriteriaList.Clear();
                    model.CriteriaList.Add(""); model.CriteriaList.Add(""); model.CriteriaList.Add(""); model.CriteriaList.Add(""); model.CriteriaList.Add(""); model.CriteriaList.Add(""); model.CriteriaList.Add("");
                    model.getCriteriaList()[6] = txtFilter.Text.Trim();

                    SearchItemsModel temp_model = ViewState["tempSearchResults"] as SearchItemsModel;
                    
                    //gets all results by item category
                    resultModel = searchControl.getSearchByItemCategory(model);

                    //filters results by value in item name text box
                    if (txtSearchItemName.Text.Trim() != "")
                    {
                        var temp_q = from i in resultModel.StationeryItemsList
                                     where i.Description.ToLower().Contains(txtSearchItemName.Text.Trim().ToLower())
                                     select i;
                        resultModel.StationeryItemsList = temp_q.ToList<StationeryItem>();
                    }

                    gvSearchItems.DataSource = resultModel.getStationeryItemsList();
                    gvSearchItems.DataBind();
                }
                    //if the existing search results have to be filtered by supplier code
                else
                {
                    int tempSupplierID = Convert.ToInt32(txtFilter.Text.Trim());
                    model.getCriteriaList()[0] = txtFilter.Text.Trim();
                    
                    //gets all item results by supplier
                    resultModel = searchControl.getSearchBySupplierID(model);

                    //filters results by value in item name text box
                    if (txtSearchItemName.Text.Trim() != "")
                    {
                        var temp_q = from i in resultModel.StationeryItemsList
                                     where i.Description.ToLower().Contains(txtSearchItemName.Text.Trim().ToLower())
                                     select i;
                        resultModel.StationeryItemsList = temp_q.ToList<StationeryItem>();
                    }

                    gvSearchItems.DataSource = resultModel.StationeryItemsList;
                    gvSearchItems.DataBind();
                
                }
            }
        }

        protected void btnSelectItems_Click(object sender, EventArgs e)
        {

            itemList = new List<StationeryItem>();
            List<string> selectedItemsId = new List<string>();
            foreach (GridViewRow gvr in gvSearchItems.Rows)
            {
                CheckBox cb = gvr.FindControl("cbSelectItem") as CheckBox;

                if (cb.Checked == true)
                {
                    string temp = gvr.Cells[0].Text;
                    selectedItemsId.Add(temp);
                    int temp_int = Convert.ToInt32(temp);
                    StationeryItem temp_item = em.StationeryItems.Where(x => x.ItemID == temp_int).FirstOrDefault();
                    itemList.Add(temp_item);

                }
            }


            //InvManagementEntities invent = new InvManagementEntities();
            //List<ShowPo> lisshow1 = new List<ShowPo>();
            //foreach (GridViewRow gvrow in gvSearchItems.Rows)
            //{
            //    ShowPo sh = new ShowPo();
            //    CheckBox chk = gvrow.FindControl("cbSelectItem") as CheckBox;
            //    if (chk.Checked == true)
            //    {

            //        sh.ItemID = int.Parse(gvrow.Cells[0].Text);
            //        sh.Description = gvrow.Cells[1].Text;

            //        int reorderqty1 = Convert.ToInt32(gvrow.Cells[0].Text);
            //        int reorderqty = (int)(from si in invent.StationeryItems
            //                               where si.ItemID == reorderqty1
            //                               select si.ReorderQty).First();
            //        sh.Qty = reorderqty;

            //        double unitprice1 = Convert.ToInt32(gvrow.Cells[0].Text);

            //        double unitprice = double.Parse((from spl in invent.SupplierPriceLists
            //                                         where spl.ItemID == unitprice1 && spl.SupplierCategory == 1
            //                                         select spl.SupplierPrice).First().ToString());

            //        sh.Price = unitprice;
            //        sh.Amount = reorderqty * unitprice;
            //        lisshow1.Add(sh);

            //    }


            //}
               // Session["SearchItemsPO"] = lisshow1;

                Session["Search_allselecteddata"] = itemList;
                Session["Search_SelectedItemsId"] = selectedItemsId;

                if (ViewState["PreviousPage"] != null)
                    if ((ViewState["PreviousPage"].ToString().Contains("StockCard.aspx")) || (ViewState["PreviousPage"].ToString().Contains("AddItemToVoucherUI.aspx")) || (ViewState["PreviousPage"].ToString().Contains("PurchaseOrders.aspx")) || (ViewState["PreviousPage"].ToString().Contains("StationeryRequisitionForm.aspx")))
                        if (Session["searchitemsmodel"] != null)
                            Session.Remove("searchitemsmodel");
        

                string prevPageUri = ViewState["PreviousPage"].ToString();
            
            if(prevPageUri.Contains("login.aspx"))
                prevPageUri = Request.Url.ToString();
            Response.Redirect(prevPageUri);

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (ViewState["PreviousPage"] != null)
                if ((ViewState["PreviousPage"].ToString().Contains("StockCard.aspx")) || (ViewState["PreviousPage"].ToString().Contains("AddItemToVoucherUI.aspx")) || (ViewState["PreviousPage"].ToString().Contains("PurchaseOrders.aspx")) || (ViewState["PreviousPage"].ToString().Contains("StationeryRequisitionForm.aspx")))
                    if (Session["searchitemsmodel"] != null)
                        Session.Remove("searchitemsmodel");
        

            string prevPageUri = ViewState["PreviousPage"].ToString();
            if (prevPageUri.Contains("login.aspx"))
                prevPageUri = Request.Url.ToString();
            Response.Redirect(prevPageUri);
        }

        protected void rbtItemCategory_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb.Checked)
            {
                if (rb.ID != "rbtSupplierID")
                {
                    divtxtFilter.Attributes.Add("onkeypress", null);
                    txtFilter.Text = null;
                }
                else
                {
                  divtxtFilter.Attributes.Add("onkeypress", "return keypress(event)");
                  txtFilter.Text = null;
                }
            }
        }



    }
}